import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {AddRolePage, AddRole, Authority} from './addRole';
import {Router} from '@angular/router';
import {UserService} from '../user/user.service';

@Injectable()
export class AddRoleService {
  public token: String;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'role/listRole'; // 查询角色列表
  private hostUrlAddRole = ParamConfig.HTTP_WEB_HOST_URL + 'role/saveRole';  // 增加角色
  private hostUrlUpdateRole = ParamConfig.HTTP_WEB_HOST_URL + 'role/updateRole'; // 修改角色
  private hostUrlDeleteRole = ParamConfig.HTTP_WEB_HOST_URL + 'role/deleteRole'; // 删除角色
  private hostUrlmenu = ParamConfig.HTTP_WEB_HOST_URL + 'resource/getTree'; // 获取菜单
  private hostUrlAllPower = ParamConfig.HTTP_WEB_HOST_URL + 'role/allotResource'; // 分配权限
  authorities: Authority[] = null;

  constructor(private http: Http, private userService: UserService, private router: Router) {
  };

// 查询角色
  getRole(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      criteria: {
        name: ''
      }
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AddRolePage();
            pagedata.addRole = body as AddRole[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 增加角色
  addURoleinfo(addRole: AddRole): Promise<any> {
    const request = JSON.stringify({
      name: addRole.name,
      remark: addRole.remark,
      sort: addRole.sort
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddRole, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 修改角色
  updateRoleinfo(addRole: AddRole): Promise<any> {
    const request = JSON.stringify({
      id: addRole.id,
      name: addRole.name,
      remark: addRole.remark,
      sort: addRole.sort
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdateRole, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 删除角色
  removeUserinfo(addRole: AddRole): Promise<any> {
    const request = JSON.stringify({
      id: addRole.id
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteRole, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 获取分配菜单
  getItemMenu(): Promise<any[] | [boolean, any]> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    const request = JSON.stringify({
      type: ''
    });
    const requestBody = 'json=' + request;
    return this.http.post(this.hostUrlmenu, requestBody, {headers: headers})
      .toPromise()
      .then(res => {
        const body = res.json();
        if (body.status === 1) {
          this.authorities = body.userTreeTo as Authority[];
          return [true, body];
        }
        if (body.status === 2) {
          alert(body.msg);
          this.router.navigate(['/login']);
        }
      })
      .catch(this.handleError);
  }

  // 分配角色
  allPower(addRole: AddRole, strAb): Promise<any> {
    const request = JSON.stringify({
      roleId: addRole.id,
      resourcesIds: strAb
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAllPower, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
